package tr.edu.ege.seagent.hobnobandroidapplication.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import tr.edu.ege.seagent.hobnobandroidapplication.Place;
import tr.edu.ege.seagent.hobnobandroidapplication.activity.LocationListActivity;
import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;

/**
 * This task retrieves location list for the selected notification or coordinate
 * list for the selected notification.
 * <p>
 * This task requires two parameters to be executed.
 * <li>selected notification URI to retrieve locations or coordinates near to
 * it.
 * <li>servlet URL of the requested operation.
 * 
 * @author etmen
 * 
 */
public class RetrieveLocationsOrCoordinatesTask extends
		AsyncTask<String, Void, ArrayList<String>> {

	private static final String TAG = "HttpAccessForLocationList";

	/**
	 * Parent {@link LocationListActivity} which will handle the task result.
	 */
	private LocationListActivity parent;

	private String servletURL;

	/**
	 * Creates a new instance of {@link RetrieveLocationsOrCoordinatesTask} with
	 * given parent activity.
	 * 
	 * @param parent
	 */
	public RetrieveLocationsOrCoordinatesTask(LocationListActivity parent) {
		this.parent = parent;
	}

	/**
	 * This method
	 * 
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	@Override
	protected ArrayList<String> doInBackground(String... args) {
		Log.i(TAG, "doInBackground METHOD");
		// client declaration...
		Log.d(TAG, "Instance of HttpClient is being created.");
		HttpClient httpclient = new DefaultHttpClient();
		// create HttpGet object for we use doGet() function...
		Log.d(TAG, "HTTP GET will be called for the notification: " + args[0]);
		// args[0] is a clicked notificationURI...
		String encodedNotificationURI = getEncodedURL(args[0]);
		servletURL = args[1];
		String getURI = servletURL + encodedNotificationURI;

		Log.d(TAG, "HTTP GET is being called with given SERVLET_URL:" + getURI);

		HttpGet get = new HttpGet(getURI);

		ArrayList<String> resultList = new ArrayList<String>();

		try {
			// getting http response...
			Log.d(TAG, "HttpResponse is being gotten.");
			HttpResponse response = httpclient.execute(get);
			// getting response's content...
			Log.d(TAG, "Location list is being gotten.");

			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is), 8);
			Place place = new Gson().fromJson(reader, Place.class);

			if (servletURL.equals(LocationListActivity.COORDINATE_SERVLET_URL)) {
				resultList = getCoordinates(place);
			} else {
				resultList = place.getPlaceURIs();
			}
		} catch (Exception e) {
			Log.wtf(TAG, e);
		}
		Log.d(TAG, "Location list is being returned.");
		return resultList;
	}

	private ArrayList<String> getCoordinates(Place place) {
		ArrayList<String> resultList = new ArrayList<String>();
		Map<String, String> coordinateMap = place.getCoordinateMap();		
		ArrayList<String> latitudes = new ArrayList<String>(place
				.getCoordinateMap().keySet());
		ArrayList<String> longitudes = new ArrayList<String>(place
				.getCoordinateMap().values());
		for (int i = 0; i < latitudes.size(); i++) {

			resultList.add(latitudes.get(i) + " " + longitudes.get(i));
		}
		return resultList;
	}

	/**
	 * This function provide us to create encoded URL.
	 * 
	 * @param clickedItem
	 * @return
	 */
	private String getEncodedURL(String clickedItem) {
		String encodedNotificationURI = "";

		try {
			encodedNotificationURI = URLEncoder.encode(clickedItem,
					"ISO-8859-1");
		} catch (UnsupportedEncodingException e1) {
			Log.wtf(TAG, e1);

		}
		return encodedNotificationURI;
	}

	/**
	 * 
	 * This function provides us to convert response's content to the string
	 * array.
	 * 
	 * @param response
	 *            HttpResponse
	 * @return ArrayList which is one row includes response's content line.
	 * 
	 */
	private ArrayList<String> convertSteamToString(HttpResponse response)
			throws IOException, UnsupportedEncodingException {

		Log.i(TAG, "convertSteamToString METHOD");
		HttpEntity entity = response.getEntity();
		Log.i(TAG, "Response content is being gotten.");
		InputStream is = entity.getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8);
		ArrayList<String> list = new ArrayList<String>();

		String line = null;
		// traverses response's content line by line...
		while ((line = reader.readLine()) != null) {
			// adds line to the list...
			Log.i(TAG, "Response line is : " + line);
			list.add(line);
		}
		is.close();
		Log.d(TAG, "List is being returned.");
		return list;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(ArrayList<String> result) {
		super.onPostExecute(result);
		if (parent != null
				&& servletURL.equals(LocationListActivity.LOCATION_SERVLET_URL)) {
			parent.processLocations(result);
		} else if (parent != null
				&& servletURL
						.equals(LocationListActivity.COORDINATE_SERVLET_URL)) {
			parent.processCoordinates(result);
		}
	}
}
